import DrawsAbstract from "../DrawsAbstract";
import gsap from "gsap";

interface renderFont{
    text: string,
    x: number,
    y: number,
    color: string
}

export default class DrawFont extends DrawsAbstract{
    drawStyle = {
        size: {
            width: 0,
            height: 0
        },
        position: {
            x: 0,
            y: 0
        },
        font: {
            eachX: 34,
            moveY: 30,
            baseY: 24,
            color: 'rgba(23,100,109, 1)',
            hideColor: 'rgba(23,100,109,0)',
            fontStyle: '24px serif',
            renderList: [] as renderFont[]
        }
    }

    constructor(ctx: CanvasRenderingContext2D, font: string, size?: {width: number, height: number}, position?: {x: number, y: number}) {
        super(ctx, size, position);
        this.changeFont(font)
    }

    realDraw() {
        this.drawEachFont()
    }

    in() {
        this.drawStyle.font.renderList.forEach((item, index) => {
            gsap.to(item, {
                duration: this.baseDuration,
                delay: index * 0.05,
                y: this.drawStyle.font.baseY,
                color: this.drawStyle.font.color
            })
        })
    }

    out() {
        this.drawStyle.font.renderList.forEach((item, index) => {
            gsap.to(item, {
                duration: this.baseDuration,
                delay: index * 0.05,
                y: this.drawStyle.font.baseY + this.drawStyle.font.moveY,
                color: this.drawStyle.font.hideColor
            })
        })
    }

    changeFont(font: string) {
        this.drawStyle.font.renderList = font.split('').reduce((all, item) => {
            if (/[\u4e00-\u9fa5]/.test(item)) {
                all.push(item)
            } else {
                if (/[\u4e00-\u9fa5]/.test(all[all.length - 1])){
                    all.push(item)
                } else {
                    all[all.length - 1] = all[all.length - 1] + item
                }
            }
            return all
        }, [] as string[]).map((item, index) => ({
            text: item,
            x: index * this.drawStyle.font.eachX,
            y: (this.drawCheck ? 0 : this.drawStyle.font.moveY) + this.drawStyle.font.baseY,
            color: this.drawCheck ? this.drawStyle.font.color : this.drawStyle.font.hideColor
        }))
    }

    private drawEachFont() {
        const font = this.drawStyle.font
        font.renderList.forEach((item) => {
            this.ctx.fillStyle = item.color;
            this.ctx.font = font.fontStyle;
            this.ctx.fillText(item.text, item.x + this.drawStyle.position.x, item.y + this.drawStyle.position.y);
        })
    }
}
